<?php
/**
* PHP SPL 观察者模式示例
*
* @author evila[keroppi1314@qq.com]
* @package jjzz.org
* @see <a href="http://cn.php.net/manual/en/class.splsubject.php" rel="nofollow">http://cn.php.net/manual/en/class.splsubject.php</a>
* @see <a href="http://cn.php.net/manual/en/class.splobserver.php" rel="nofollow">http://cn.php.net/manual/en/class.splobserver.php</a>
*/

/**
* 观察者类
*
*/
class DemoSubject implements SplSubject
{
private $observers,$value;

public function __construct()
{
$this->observers = array();
}

/**
* 注册订阅者
*
* @param SplObserver $observer
*/
public function attach(SplObserver $observer)
{
$this->observers[] = $observer;
}

/**
* 注销订阅者
*
* @param SplObserver $observer
*/
public function detach(SplObserver $observer)
{
if ($idx = array_search($observer , $this->observers, true))
{
unset($this->observers[$idx]);
}
}

/**
* 发生变化时通知订阅者有更新
*
*/
public function notify()
{
foreach ($this->observers as $observer)
{
$observer->update($this);
}
}

/**
* 演示：设置一个值，并执行通知方法
*
* @param unknown_type $value
*/
public function setValue($value)
{
$this->value = $value;
$this->notify();
}

/**
* 演示：输出发生变化后的结果
*
* @return unknown
*/
public function getValue()
{
return $this->value;
}
}

/**
* 订阅者类
*
*/
class DemoObserver implements SplObserver
{
/**
* 处理观察者提交的数据
*
* @param SplSubject $subject
*/
public function update(SplSubject $subject)
{
echo ‘<br />The new value is:’.$subject->getValue();
}
}

$subject = new DemoSubject(); //观察者实例
$observer1 = new DemoObserver(); //订阅者1
$observer2 = new DemoObserver(); //订阅者2

$subject->attach($observer1); //订阅
$subject->attach($observer2); //订阅

$subject->setValue(12); //观者者发生变化

?>